package org.dromara.system.service.impl;

import cn.dev33.satoken.context.SaHolder;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheConstants;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.DictService;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.system.domain.SysDictData;
import org.dromara.system.domain.SysDictType;
import org.dromara.system.mapper.SysDictDataMapper;
import org.dromara.system.mapper.SysDictTypeMapper;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 */
@RequiredArgsConstructor
@Service
public class SysDictTypeServiceImpl implements DictService {

  private final SysDictTypeMapper baseMapper;
  private final SysDictDataMapper dictDataMapper;

  public TableDataInfo<SysDictType> selectPageDictTypeList(SysDictType dictType, PageQuery pageQuery) {
    LambdaQueryWrapper<SysDictType> lqw = buildQueryWrapper(dictType);

    Page<SysDictType> page = pageQuery.build();
    Page<SysDictType > result = baseMapper.selectPage(page, lqw);

    return  TableDataInfo.build(result);

  }

  /**
   * 根据条件分页查询字典类型
   *
   * @param dictType 字典类型信息
   * @return 字典类型集合信息
   */
  public List<SysDictType> selectDictTypeList(SysDictType dictType) {
    LambdaQueryWrapper<SysDictType> lqw = buildQueryWrapper(dictType);

    return baseMapper.selectList(lqw);
//    return dictTypeNewStyleMapper.queryPageList(dictType);
//    LambdaQueryWrapper<SysDictType> lqw = buildQueryWrapper(dictType);
//    return baseMapper.selectVoList(lqw);
  }

  private LambdaQueryWrapper<SysDictType> buildQueryWrapper(SysDictType bo) {
    Map<String, Object> params = bo.getParams();
    LambdaQueryWrapper<SysDictType> lqw = Wrappers.lambdaQuery();
    lqw.like(StringUtils.isNotBlank(bo.getName()), SysDictType::getName, bo.getName());
    lqw.like(StringUtils.isNotBlank(bo.getType()), SysDictType::getType, bo.getType());
    lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
        SysDictType::getCreateTime, params.get("beginTime"), params.get("endTime"));
    lqw.orderByAsc(SysDictType::getDictId);
    return lqw;
  }

  /**
   * 根据所有字典类型
   *
   * @return 字典类型集合信息
   */
  public List<SysDictType> selectDictTypeAll() {
    return baseMapper.selectList();

//    return baseMapper.selectVoList();
  }

  /**
   * 根据字典类型查询字典数据
   *
   * @param type 字典类型
   * @return 字典数据集合信息
   */
  @Cacheable(cacheNames = CacheNames.SYS_DICT, key = "#type")
  public List<SysDictData> selectDictDataByType(String type) {
    List<SysDictData> dictDatas = dictDataMapper.selectList(new LambdaQueryWrapper<SysDictData>()
      .eq(SysDictData::getType, type)
      .orderByAsc(SysDictData::getSort));
    if (ObjectUtil.isNotNull(dictDatas)) {
      return dictDatas;
    }
    return null;
  }

  /**
   * 根据字典类型ID查询信息
   *
   * @param dictId 字典类型ID
   * @return 字典类型
   */
  public SysDictType selectDictTypeById(Long dictId) {
    return baseMapper.selectById(dictId);
  }

  /**
   * 根据字典类型查询信息
   *
   * @param dictType 字典类型
   * @return 字典类型
   */
  public SysDictType selectDictTypeByType(String dictType) {
    return baseMapper.selectOne(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getType, dictType));
  }

  /**
   * 批量删除字典类型信息
   *
   * @param dictIds 需要删除的字典ID
   */
  public void deleteDictTypeByIds(Long[] dictIds) {
    for (Long dictId : dictIds) {
      SysDictType dictType = baseMapper.selectById(dictId);
      if (dictDataMapper.exists(new LambdaQueryWrapper<SysDictData>()
          .eq(SysDictData::getType, dictType.getType()))) {
        throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getName()));
      }
      CacheUtils.evict(CacheNames.SYS_DICT, dictType.getType());
    }
    baseMapper.deleteBatchIds(Arrays.asList(dictIds));
  }

  /**
   * 重置字典缓存数据
   */
  public void resetDictCache() {
    CacheUtils.clear(CacheNames.SYS_DICT);
  }

  /**
   * 新增保存字典类型信息
   *
   * @param bo 字典类型信息
   * @return 结果
   */
  @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#bo.type")
  public List<SysDictData> insertDictType(SysDictType bo) {
//    SysDictType dict = MapstructUtils.convert(bo, SysDictType.class);
    int row = baseMapper.insert(bo);
    if (row > 0) {
      // 新增 type 下无 data 数据 返回空防止缓存穿透
      return new ArrayList<>();
    }
    throw new ServiceException("操作失败");
  }

  /**
   * 修改保存字典类型信息
   *
   * @param bo 字典类型信息
   * @return 结果
   */
  @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#bo.type")
  @Transactional(rollbackFor = Exception.class)
  public List<SysDictData> updateDictType(SysDictType bo) {
//    SysDictType dict = MapstructUtils.convert(bo, SysDictType.class);
    SysDictType oldDict = baseMapper.selectById(bo.getDictId());
    dictDataMapper.update(null, new LambdaUpdateWrapper<SysDictData>()
        .set(SysDictData::getType, bo.getType())
        .eq(SysDictData::getType, oldDict.getType()));
    int row = baseMapper.updateById(bo);
    if (row > 0) {
      CacheUtils.evict(CacheNames.SYS_DICT, oldDict.getType());
      return dictDataMapper.selectList(new LambdaQueryWrapper<SysDictData>()
        .eq(SysDictData::getType, bo.getType())
        .orderByAsc(SysDictData::getSort));
//      return dictDataMapper.selectDictDataByType(dict.getDictType());
    }
    throw new ServiceException("操作失败");
  }

  /**
   * 校验字典类型称是否唯一
   *
   * @param dictType 字典类型
   * @return 结果
   */
  public boolean checkDictTypeUnique(SysDictType dictType) {
    boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysDictType>()
        .eq(SysDictType::getType, dictType.getType())
        .ne(ObjectUtil.isNotNull(dictType.getDictId()), SysDictType::getDictId, dictType.getDictId()));
    return !exist;
  }
  /**
   * 根据字典类型和字典值获取字典标签
   *
   * @param dictType  字典类型
   * @param dictValue 字典值
   * @param separator 分隔符
   * @return 字典标签
   */
  @SuppressWarnings("unchecked cast")
  @Override
  public String getDictLabel(String dictType, String dictValue, String separator) {
    // 优先从本地缓存获取
    List<SysDictData> datas = (List<SysDictData>) SaHolder.getStorage().get(CacheConstants.SYS_DICT_KEY + dictType);
    if (ObjectUtil.isNull(datas)) {
      datas = SpringUtils.getAopProxy(this).selectDictDataByType(dictType);
      SaHolder.getStorage().set(CacheConstants.SYS_DICT_KEY + dictType, datas);
    }

    Map<String, String> map = StreamUtils.toMap(datas, SysDictData::getValue, SysDictData::getName);
    if (StringUtils.containsAny(dictValue, separator)) {
      return Arrays.stream(dictValue.split(separator))
          .map(v -> map.getOrDefault(v, StringUtils.EMPTY))
          .collect(Collectors.joining(separator));
    } else {
      return map.getOrDefault(dictValue, StringUtils.EMPTY);
    }
  }

  /**
   * 根据字典类型和字典标签获取字典值
   *
   * @param dictType  字典类型
   * @param dictLabel 字典标签
   * @param separator 分隔符
   * @return 字典值
   */
  @SuppressWarnings("unchecked cast")
  @Override
  public String getDictValue(String dictType, String dictLabel, String separator) {
    // 优先从本地缓存获取
    List<SysDictData> datas = (List<SysDictData>) SaHolder.getStorage().get(CacheConstants.SYS_DICT_KEY + dictType);
    if (ObjectUtil.isNull(datas)) {
      datas = SpringUtils.getAopProxy(this).selectDictDataByType(dictType);
      SaHolder.getStorage().set(CacheConstants.SYS_DICT_KEY + dictType, datas);
    }

    Map<String, String> map = StreamUtils.toMap(datas, SysDictData::getName, SysDictData::getValue);
    if (StringUtils.containsAny(dictLabel, separator)) {
      return Arrays.stream(dictLabel.split(separator))
          .map(l -> map.getOrDefault(l, StringUtils.EMPTY))
          .collect(Collectors.joining(separator));
    } else {
      return map.getOrDefault(dictLabel, StringUtils.EMPTY);
    }
  }

  @Override
  public Map<String, String> getAllDictByDictType(String dictType) {
    List<SysDictData> list = selectDictDataByType(dictType);
    return StreamUtils.toMap(list, SysDictData::getValue, SysDictData::getName);
  }

}
